#!/usr/bin/env python

import threading
import time
import sys
import Queue
import socket
import pickle
from configobj import ConfigObj
from SmsModem import *
from Sms import *

MAX = 4096

class SmsCommander(threading.Thread):
    def __init__(self):
	threading.Thread.__init__(self)
	try:
	    self._smsModule = SmsModem()
	except Exception, e:
	    print "modem not connected: \n\t", e
	    sys.exit(0)
	self.readConfig()
	self.connectToLoadbalancer()
    def readConfig(self):
	config = ConfigObj("config")
	self._loadbalancerIp = config['loadbalancer']['ip']
	self._loadbalancerPort = int(config['loadbalancer']['port'])
    def connectToLoadbalancer(self):
	""" create a TCP/IP connection with LoadBalancer """
	try:
	    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	    s.connect( (self._loadbalancerIp, self._loadbalancerPort) )
	    s.setblocking(0)
	    self._socket = s
	    print "SmsCommander: successfully connected to loadbalancer"
	except Exception, e:
	    print "SmsCommander: couldnt connect to loadbalancer"
	    print e
	    sys.exit(0)
    def sendToLoadbalancer(self, sms): 
	print "sending to loadbalancer [%s]" %sms
	pickledSms = pickle.dumps(sms);
	try: 
	    self._socket.send(pickledSms)
	except Exception, e:
	    print "couldnt send"
    def recvFromLoadbalancer(self):
	try: 
	    data = self._socket.recv(MAX)
	    #print "SmsCommander.recvFromLoadbalancer: [%s]" %pickle.loads(data)
	    print ">> SmsCommander.recvFromLoadbalancer: [%s]" \
			%pickle.loads(data).getNumber()
	    return pickle.loads(data)
	except Exception, e:
	    #print "SmsCommander.recvFromLoadbalancer: no data"
	    return None
    def run(self):
	print "---------------------------"
	while 1:
	    # get messages from LoadBalancer
	    while 1:
		msg1 = self.recvFromLoadbalancer()
		if msg1 is not None:
		    print "SmsCommander:msg [%s]" %msg1
		    print "---------------------------"
		if msg1==None:
		    break
		self._smsModule.putSmsOnSendQueue(msg1)
		print "SmsCommander: msg on sending queue"
	    # send answers to LoadBallancer
	    try:
		msg2 = self._smsModule.getSmsFromReciveQueue()
		while msg2: 
		    self.sendToLoadbalancer(msg2)
		    msg2 = self._smsModule.getSmsFromReciveQueue()
	    except Exception, e:
		pass
		#print "all messages sent to loadbalancer"
	    time.sleep(2);

def main():
    print "SmsCommander: started"
    SmsCommander().start()

if __name__=='__main__':
    main()


